package com.phonetools.commonutils.number

import java.nio.ByteBuffer
import java.nio.ByteOrder

fun Collection<Short>.toShortArray(fixLen: Int): ShortArray {
    val tmp = this.toShortArray()
    return when {
        tmp.size == fixLen -> {
            tmp
        }
        tmp.size > fixLen -> {
            tmp.sliceArray(0 until fixLen)
        }
        tmp.size < fixLen -> {
            tmp + ShortArray(fixLen - tmp.size)
        }
        else -> {
            ShortArray(fixLen)
        }
    }
}

fun ByteArray.toShortArray(): ShortArray {
    val count = this.size shr 1
    val dest = ShortArray(count)
    for (i in 0 until count) {
        dest[i] =
            (this[i * 2].toInt() and 0xff or (this[2 * i + 1].toInt() and 0xff shl 8)).toShort()
    }
    return dest
}

fun ShortArray.toByteArray(): ByteArray {
    val byteArr = ByteArray(this.size * 2)
    ByteBuffer.wrap(byteArr).order(ByteOrder.LITTLE_ENDIAN).asShortBuffer().put(this)
    return byteArr
}